import { reqAddUser, reqUpdateUser } from "@/api/reqUser"
import type { USER, USERForm } from "@/types/user"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { ref, reactive, type Ref } from "vue"

export const useUserForm = (
  getUserByPage: any,
  nowPageRef: Ref<number>,
  sizeRef: Ref<number>
) => {
  //-------------公共数据开始-----------------
  // 弹窗标题
  const titleRef = ref("添加用户")
  // 弹窗控制数据
  const userDialog = ref(false)

  // 定义用户表单的数据
  const userRef = ref<USERForm>({
    username: "",
    name: "",
    role_id: "",
    phone: "",
  })
  // 表单对象
  const userFormEle = ref<FormInstance>()

  // 表单校验
  const userRules = reactive<FormRules<USERForm>>({
    username: [
      {
        required: true,
        message: "请输入用户名",
        trigger: "blur",
      },
      {
        pattern: /^[a-zA-Z0-9]+$/,
        message: "用户名只能为数字和字母",
        trigger: "blur",
      },
    ],
    name: [
      {
        required: true,
        message: "请输入昵称",
        trigger: "blur",
      },
    ],
  })

  // 点击关闭
  const close = () => {
    // userFormEle.value?.resetFields()
    userRef.value = {
      name: "",
      username: "",
      role_id: "",
      phone: "",
    }
    userDialog.value = false
  }

  // 点击添加按钮
  const addUserHandler = () => {
    userDialog.value = true
    titleRef.value = "添加用户"
  }
  // 点击确定
  const addUser = () => {
    userFormEle.value?.validate(async (isOk) => {
      if (isOk) {
        const { msg, status } = await reqAddUser(userRef.value)
        if (status === 0) {
          ElMessage.success("添加成功")
          // 重新获取
          getUserByPage(nowPageRef.value, sizeRef.value)
          close()
        } else {
          ElMessage.error(msg)
        }
      }
    })
  }

  // ------------------修改用户的逻辑-----------------
  const updateUserHandler = (user: USER) => {
    userDialog.value = true
    titleRef.value = "修改用户"
    // 记录要更新的用户对象
    // 大类型给小类型赋值
    userRef.value = {
      ...user,
    }
  }

  // 更新用户
  const updateUser = () => {
    userFormEle.value?.validate(async (isOk) => {
      if (isOk) {
        const { status } = await reqUpdateUser(userRef.value)
        if (status === 0) {
          ElMessage.success("修改成功")
          // 重新获取当前页的数据
          getUserByPage(nowPageRef.value, sizeRef.value)
          close()
        }
      }
    })
  }

  const addAndUPdate = () => {
    if (titleRef.value === "添加用户") {
      addUser()
    } else {
      updateUser()
    }
  }

  return {
    close,
    addUser,
    addUserHandler,
    updateUser,
    updateUserHandler,
    addAndUPdate,
    userDialog,
    userFormEle,
    userRef,
    titleRef,
    userRules,
  }
}
